import Promise from 'promise';
import * as ResultMsg from '../constrants/ResultMsg';
import { StaticModel } from '../models';

const fields = '_id appId name title content isHtml isContrast create_at';

export function find(appId, conditions, options) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof conditions !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  if (typeof options !== 'object') options = null;
  conditions.appId = appId;
  const query = StaticModel.find(conditions).select(fields).setOptions(options);
  return query.exec();
}

export function findOneById(appId, id) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof id !== 'string' && typeof id !== 'object') throw new Error(ResultMsg.NO_ID);
  const query = StaticModel.findOne({ appId, _id: id }).select(fields);
  return query.exec();
}

export function findOneByName(appId, name) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof name !== 'string') throw new Error(ResultMsg.NOT_STRING);
  const query = StaticModel.findOne({ appId, name }).select(fields);
  return query.exec();
}

export function update(appId, id, data) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof id !== 'string' && typeof id !== 'object') throw new Error(ResultMsg.NO_ID);
  if (typeof data !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  const query = StaticModel.findByIdAndUpdate(id, { $set: data });
  return query.exec();
}

export function create(appId, { name, title, content, isHtml, isContrast }) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof name !== 'string'
    || typeof title !== 'string'
    || typeof content !== 'string') {
    throw new Error(ResultMsg.NOT_STRING);
  }

  if (typeof isHtml === undefined || typeof isContrast === undefined) {
    throw new Error(ResultMsg.NOT_BOOLEAN);
  }

  const doc = new StaticModel();
  doc.appId = appId;
  doc.name = name;
  doc.title = title;
  doc.content = content;
  doc.isHtml = isHtml;
  doc.isContrast = isContrast;
  return doc.save();
}

export function remove(appId, conditions) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof conditions !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  conditions.appId = appId;
  return StaticModel.find(conditions).remove().exec();
}

export async function removeById(appId, id) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof id !== 'string' && typeof id !== 'object') throw new Error(ResultMsg.NO_ID);
  return StaticModel.find({ appId, _id: id }).remove().exec();
}

export async function removeByName(appId, name) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof id !== 'string' && typeof id !== 'object') throw new Error(ResultMsg.NO_ID);
  return StaticModel.find({ appId, name }).remove().exec();
}

